3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 namespace Wikimedia\Rdbms
;
38 class DatabaseSqlite
extends Database
{
39 /** @var string|null Directory for SQLite database files listed under their DB name */
41 /** @var string|null Explicit path for the SQLite database file */
43 /** @var string Transaction mode */
46 /** @var int The number of rows affected as an integer */
47 protected $lastAffectedRowCount;
49 protected $lastResultHandle;
54 /** @var FSLockManager (hopefully on the same server as the DB) */
57 /** @var array List of shared database already attached to this connection */
58 private $alreadyAttached = [];
60 /** @var bool Whether full text is enabled */
61 private static $fulltextEnabled = null;
63 /** @var string[] See https://www.sqlite.org/lang_transaction.html */
64 private static $VALID_TRX_MODES = [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ];
67 * Additional params include:
68 * - dbDirectory : directory containing the DB and the lock file directory
69 * - dbFilePath : use this to force the path of the DB file
70 * - trxMode : one of (deferred, immediate, exclusive)
73 public function __construct( array $p ) {
74 if ( isset( $p['dbFilePath'] ) ) {
75 $this->dbPath
= $p['dbFilePath'];
76 if ( !strlen( $p['dbname'] ) ) {
77 $p['dbname'] = self
::generateDatabaseName( $this->dbPath
);
79 } elseif ( isset( $p['dbDirectory'] ) ) {
80 $this->dbDir
= $p['dbDirectory'];
83 parent
::__construct( $p );
85 $this->trxMode
= strtoupper( $p['trxMode'] ??
'' );
87 $lockDirectory = $this->getLockFileDirectory();
88 if ( $lockDirectory !== null ) {
89 $this->lockMgr
= new FSLockManager( [
90 'domain' => $this->getDomainID(),
91 'lockDirectory' => $lockDirectory
94 $this->lockMgr
= new NullLockManager( [ 'domain' => $this->getDomainID() ] );
98 protected static function getAttributes() {
99 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
103 * @param string $filename
104 * @param array $p Options map; supports:
105 * - flags : (same as __construct counterpart)
106 * - trxMode : (same as __construct counterpart)
107 * - dbDirectory : (same as __construct counterpart)
108 * @return DatabaseSqlite
111 public static function newStandaloneInstance( $filename, array $p = [] ) {
112 $p['dbFilePath'] = $filename;
114 $p['tablePrefix'] = '';
115 /** @var DatabaseSqlite $db */
116 $db = Database
::factory( 'sqlite', $p );
124 public function getType() {
128 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
131 // Note that for SQLite, $server, $user, and $pass are ignored
133 if ( $schema !== null ) {
134 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
137 if ( $this->dbPath
!== null ) {
138 $path = $this->dbPath
;
139 } elseif ( $this->dbDir
!== null ) {
140 $path = self
::generateFileName( $this->dbDir
, $dbName );
142 throw $this->newExceptionAfterConnectError( "DB path or directory required" );
145 if ( !self
::isProcessMemoryPath( $path ) && !is_readable( $path ) ) {
146 throw $this->newExceptionAfterConnectError( 'SQLite database file is not readable' );
147 } elseif ( !in_array( $this->trxMode
, self
::$VALID_TRX_MODES, true ) ) {
148 throw $this->newExceptionAfterConnectError( "Got mode '{$this->trxMode}' for BEGIN" );
152 if ( $this->getFlag( self
::DBO_PERSISTENT
) ) {
153 // Persistent connections can avoid some schema index reading overhead.
154 // On the other hand, they can cause horrible contention with DBO_TRX.
155 if ( $this->getFlag( self
::DBO_TRX
) ||
$this->getFlag( self
::DBO_DEFAULT
) ) {
156 $this->connLogger
->warning(
157 __METHOD__
. ": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
158 $this->getLogContext()
161 $attributes[PDO
::ATTR_PERSISTENT
] = true;
166 $this->conn
= new PDO( "sqlite:$path", null, null, $attributes );
167 } catch ( PDOException
$e ) {
168 throw $this->newExceptionAfterConnectError( $e->getMessage() );
171 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
174 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
175 // Enforce LIKE to be case sensitive, just like MySQL
176 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
177 // Apply optimizations or requirements regarding fsync() usage
178 $sync = $this->connectionVariables
['synchronous'] ??
null;
179 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
180 $this->query( "PRAGMA synchronous = $sync", __METHOD__
, $flags );
182 } catch ( Exception
$e ) {
183 throw $this->newExceptionAfterConnectError( $e->getMessage() );
188 * @return string|null SQLite DB file path
189 * @throws DBUnexpectedError
192 public function getDbFilePath() {
193 return $this->dbPath ?? self
::generateFileName( $this->dbDir
, $this->getDBname() );
197 * @return string|null Lock file directory
199 public function getLockFileDirectory() {
200 if ( $this->dbPath
!== null && !self
::isProcessMemoryPath( $this->dbPath
) ) {
201 return dirname( $this->dbPath
) . '/locks';
202 } elseif ( $this->dbDir
!== null && !self
::isProcessMemoryPath( $this->dbDir
) ) {
203 return $this->dbDir
. '/locks';
210 * Does not actually close the connection, just destroys the reference for GC to do its work
213 protected function closeConnection() {
220 * Generates a database file name. Explicitly public for installer.
221 * @param string $dir Directory where database resides
222 * @param string|bool $dbName Database name (or false from Database::factory, validated here)
224 * @throws DBUnexpectedError
226 public static function generateFileName( $dir, $dbName ) {
228 throw new DBUnexpectedError( null, __CLASS__
. ": no DB directory specified" );
229 } elseif ( self
::isProcessMemoryPath( $dir ) ) {
230 throw new DBUnexpectedError(
232 __CLASS__
. ": cannot use process memory directory '$dir'"
234 } elseif ( !strlen( $dbName ) ) {
235 throw new DBUnexpectedError( null, __CLASS__
. ": no DB name specified" );
238 return "$dir/$dbName.sqlite";
242 * @param string $path
245 private static function generateDatabaseName( $path ) {
246 if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
247 // E.g. "file::memory:?cache=shared" => ":memory":
249 } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
250 // E.g. "file:memdb1?mode=memory" => ":memdb1:"
253 // E.g. "/home/.../some_db.sqlite3" => "some_db"
254 return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
259 * @param string $path
262 private static function isProcessMemoryPath( $path ) {
263 return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
267 * Check if the searchindext table is FTS enabled.
268 * @return bool False if not enabled.
270 public function checkForEnabledSearch() {
271 if ( self
::$fulltextEnabled === null ) {
272 self
::$fulltextEnabled = false;
273 $table = $this->tableName( 'searchindex' );
275 "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'",
277 self
::QUERY_IGNORE_DBO_TRX
280 $row = $res->fetchRow();
281 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
285 return self
::$fulltextEnabled;
289 * Returns version of currently supported SQLite fulltext search module or false if none present.
292 static function getFulltextSearchModule() {
293 static $cachedResult = null;
294 if ( $cachedResult !== null ) {
295 return $cachedResult;
297 $cachedResult = false;
298 $table = 'dummy_search_test';
300 $db = self
::newStandaloneInstance( ':memory:' );
301 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
302 $cachedResult = 'FTS3';
306 return $cachedResult;
310 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
313 * @param string $name Database name to be used in queries like
314 * SELECT foo FROM dbname.table
315 * @param bool|string $file Database file name. If omitted, will be generated
316 * using $name and configured data directory
317 * @param string $fname Calling function name
318 * @return IResultWrapper
320 public function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
321 $file = is_string( $file ) ?
$file : self
::generateFileName( $this->dbDir
, $name );
322 $encFile = $this->addQuotes( $file );
325 "ATTACH DATABASE $encFile AS $name",
327 self
::QUERY_IGNORE_DBO_TRX
331 protected function isWriteQuery( $sql ) {
332 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
335 protected function isTransactableQuery( $sql ) {
336 return parent
::isTransactableQuery( $sql ) && !in_array(
337 $this->getQueryVerb( $sql ),
338 [ 'ATTACH', 'PRAGMA' ],
344 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
347 * @return bool|IResultWrapper
349 protected function doQuery( $sql ) {
350 $res = $this->getBindingHandle()->query( $sql );
351 if ( $res === false ) {
355 $resource = ResultWrapper
::unwrap( $res );
356 $this->lastAffectedRowCount
= $resource->rowCount();
357 $res = new ResultWrapper( $this, $resource->fetchAll() );
363 * @param IResultWrapper|mixed $res
365 function freeResult( $res ) {
366 if ( $res instanceof ResultWrapper
) {
372 * @param IResultWrapper|array $res
373 * @return stdClass|bool
375 function fetchObject( $res ) {
376 $resource =& ResultWrapper
::unwrap( $res );
378 $cur = current( $resource );
379 if ( is_array( $cur ) ) {
382 foreach ( $cur as $k => $v ) {
383 if ( !is_numeric( $k ) ) {
395 * @param IResultWrapper|mixed $res
398 function fetchRow( $res ) {
399 $resource =& ResultWrapper
::unwrap( $res );
400 $cur = current( $resource );
401 if ( is_array( $cur ) ) {
411 * The PDO::Statement class implements the array interface so count() will work
413 * @param IResultWrapper|array|false $res
416 function numRows( $res ) {
417 // false does not implement Countable
418 $resource = ResultWrapper
::unwrap( $res );
420 return is_array( $resource ) ?
count( $resource ) : 0;
424 * @param IResultWrapper $res
427 function numFields( $res ) {
428 $resource = ResultWrapper
::unwrap( $res );
429 if ( is_array( $resource ) && count( $resource ) > 0 ) {
430 // The size of the result array is twice the number of fields. (T67578)
431 return count( $resource[0] ) / 2;
433 // If the result is empty return 0
439 * @param IResultWrapper $res
443 function fieldName( $res, $n ) {
444 $resource = ResultWrapper
::unwrap( $res );
445 if ( is_array( $resource ) ) {
446 $keys = array_keys( $resource[0] );
455 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
457 * @param string $name
458 * @param string $format
461 function tableName( $name, $format = 'quoted' ) {
462 // table names starting with sqlite_ are reserved
463 if ( strpos( $name, 'sqlite_' ) === 0 ) {
467 return str_replace( '"', '', parent
::tableName( $name, $format ) );
471 * This must be called after nextSequenceVal
475 function insertId() {
476 // PDO::lastInsertId yields a string :(
477 return intval( $this->getBindingHandle()->lastInsertId() );
481 * @param IResultWrapper|array $res
484 function dataSeek( $res, $row ) {
485 $resource =& ResultWrapper
::unwrap( $res );
488 for ( $i = 0; $i < $row; $i++
) {
497 function lastError() {
498 if ( !is_object( $this->conn
) ) {
499 return "Cannot return last error, no db connection";
501 $e = $this->conn
->errorInfo();
509 function lastErrno() {
510 if ( !is_object( $this->conn
) ) {
511 return "Cannot return last error, no db connection";
513 $info = $this->conn
->errorInfo();
522 protected function fetchAffectedRowCount() {
523 return $this->lastAffectedRowCount
;
526 function tableExists( $table, $fname = __METHOD__
) {
527 $tableRaw = $this->tableName( $table, 'raw' );
528 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
529 return true; // already known to exist
532 $encTable = $this->addQuotes( $tableRaw );
534 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
536 self
::QUERY_IGNORE_DBO_TRX
539 return $res->numRows() ?
true : false;
543 * Returns information about an index
544 * Returns false if the index does not exist
545 * - if errors are explicitly ignored, returns NULL on failure
547 * @param string $table
548 * @param string $index
549 * @param string $fname
550 * @return array|false
552 function indexInfo( $table, $index, $fname = __METHOD__
) {
553 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
554 $res = $this->query( $sql, $fname, self
::QUERY_IGNORE_DBO_TRX
);
555 if ( !$res ||
$res->numRows() == 0 ) {
559 foreach ( $res as $row ) {
560 $info[] = $row->name
;
567 * @param string $table
568 * @param string $index
569 * @param string $fname
572 function indexUnique( $table, $index, $fname = __METHOD__
) {
573 $row = $this->selectRow( 'sqlite_master', '*',
576 'name' => $this->indexName( $index ),
578 if ( !$row ||
!isset( $row->sql
) ) {
582 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
583 $indexPos = strpos( $row->sql
, 'INDEX' );
584 if ( $indexPos === false ) {
587 $firstPart = substr( $row->sql
, 0, $indexPos );
588 $options = explode( ' ', $firstPart );
590 return in_array( 'UNIQUE', $options );
594 * Filter the options used in SELECT statements
596 * @param array $options
599 function makeSelectOptions( $options ) {
600 foreach ( $options as $k => $v ) {
601 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
606 return parent
::makeSelectOptions( $options );
610 * @param array $options
613 protected function makeUpdateOptionsArray( $options ) {
614 $options = parent
::makeUpdateOptionsArray( $options );
615 $options = self
::fixIgnore( $options );
621 * @param array $options
624 static function fixIgnore( $options ) {
625 # SQLite uses OR IGNORE not just IGNORE
626 foreach ( $options as $k => $v ) {
627 if ( $v == 'IGNORE' ) {
628 $options[$k] = 'OR IGNORE';
636 * @param array $options
639 function makeInsertOptions( $options ) {
640 $options = self
::fixIgnore( $options );
642 return parent
::makeInsertOptions( $options );
646 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
647 * @param string $table
649 * @param string $fname
650 * @param array $options
653 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
654 if ( !count( $a ) ) {
658 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
659 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
660 $affectedRowCount = 0;
662 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
663 foreach ( $a as $v ) {
664 parent
::insert( $table, $v, "$fname/multi-row", $options );
665 $affectedRowCount +
= $this->affectedRows();
667 $this->endAtomic( $fname );
668 } catch ( Exception
$e ) {
669 $this->cancelAtomic( $fname );
672 $this->affectedRowCount
= $affectedRowCount;
674 parent
::insert( $table, $a, "$fname/single-row", $options );
681 * @param string $table
682 * @param array $uniqueIndexes Unused
683 * @param string|array $rows
684 * @param string $fname
686 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
687 if ( !count( $rows ) ) {
691 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
692 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
693 $affectedRowCount = 0;
695 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
696 foreach ( $rows as $v ) {
697 $this->nativeReplace( $table, $v, "$fname/multi-row" );
698 $affectedRowCount +
= $this->affectedRows();
700 $this->endAtomic( $fname );
701 } catch ( Exception
$e ) {
702 $this->cancelAtomic( $fname );
705 $this->affectedRowCount
= $affectedRowCount;
707 $this->nativeReplace( $table, $rows, "$fname/single-row" );
712 * Returns the size of a text field, or -1 for "unlimited"
713 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
715 * @param string $table
716 * @param string $field
719 function textFieldSize( $table, $field ) {
726 function unionSupportsOrderAndLimit() {
731 * @param string[] $sqls
732 * @param bool $all Whether to "UNION ALL" or not
735 function unionQueries( $sqls, $all ) {
736 $glue = $all ?
' UNION ALL ' : ' UNION ';
738 return implode( $glue, $sqls );
744 function wasDeadlock() {
745 return $this->lastErrno() == 5; // SQLITE_BUSY
751 function wasReadOnlyError() {
752 return $this->lastErrno() == 8; // SQLITE_READONLY;
755 public function wasConnectionError( $errno ) {
756 return $errno == 17; // SQLITE_SCHEMA;
759 protected function wasKnownStatementRollbackError() {
760 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
761 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
762 // https://sqlite.org/lang_createtable.html#uniqueconst
763 // https://sqlite.org/lang_conflict.html
767 public function serverIsReadOnly() {
768 $path = $this->getDbFilePath();
770 return ( !self
::isProcessMemoryPath( $path ) && !is_writable( $path ) );
774 * @return string Wikitext of a link to the server software's web site
776 public function getSoftwareLink() {
777 return "[{{int:version-db-sqlite-url}} SQLite]";
781 * @return string Version information from the database
783 function getServerVersion() {
784 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
790 * Get information about a given field
791 * Returns false if the field does not exist.
793 * @param string $table
794 * @param string $field
795 * @return SQLiteField|bool False on failure
797 function fieldInfo( $table, $field ) {
798 $tableName = $this->tableName( $table );
799 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
800 $res = $this->query( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
801 foreach ( $res as $row ) {
802 if ( $row->name
== $field ) {
803 return new SQLiteField( $row, $tableName );
810 protected function doBegin( $fname = '' ) {
811 if ( $this->trxMode
!= '' ) {
812 $this->query( "BEGIN {$this->trxMode}", $fname );
814 $this->query( 'BEGIN', $fname );
822 function strencode( $s ) {
823 return substr( $this->addQuotes( $s ), 1, -1 );
830 function encodeBlob( $b ) {
831 return new Blob( $b );
835 * @param Blob|string $b
838 function decodeBlob( $b ) {
839 if ( $b instanceof Blob
) {
847 * @param string|int|null|bool|Blob $s
850 function addQuotes( $s ) {
851 if ( $s instanceof Blob
) {
852 return "x'" . bin2hex( $s->fetch() ) . "'";
853 } elseif ( is_bool( $s ) ) {
855 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
856 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
857 // This is a known limitation of SQLite's mprintf function which PDO
858 // should work around, but doesn't. I have reported this to php.net as bug #63419:
859 // https://bugs.php.net/bug.php?id=63419
860 // There was already a similar report for SQLite3::escapeString, bug #62361:
861 // https://bugs.php.net/bug.php?id=62361
862 // There is an additional bug regarding sorting this data after insert
863 // on older versions of sqlite shipped with ubuntu 12.04
864 // https://phabricator.wikimedia.org/T74367
865 $this->queryLogger
->debug(
867 ': Quoting value containing null byte. ' .
868 'For consistency all binary data should have been ' .
869 'first processed with self::encodeBlob()'
871 return "x'" . bin2hex( (string)$s ) . "'";
873 return $this->getBindingHandle()->quote( (string)$s );
877 public function buildSubstring( $input, $startPosition, $length = null ) {
878 $this->assertBuildSubstringParams( $startPosition, $length );
879 $params = [ $input, $startPosition ];
880 if ( $length !== null ) {
883 return 'SUBSTR(' . implode( ',', $params ) . ')';
887 * @param string $field Field or column to cast
891 public function buildStringCast( $field ) {
892 return 'CAST ( ' . $field . ' AS TEXT )';
896 * No-op version of deadlockLoop
900 public function deadlockLoop( /*...*/ ) {
901 $args = func_get_args();
902 $function = array_shift( $args );
904 return $function( ...$args );
911 protected function replaceVars( $s ) {
912 $s = parent
::replaceVars( $s );
913 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
914 // CREATE TABLE hacks to allow schema file sharing with MySQL
916 // binary/varbinary column type -> blob
917 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
918 // no such thing as unsigned
919 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
921 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
922 // floating point types -> REAL
924 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
929 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
930 // TEXT normalization
931 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
932 // BLOB normalization
933 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
935 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
937 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
939 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
940 // binary collation type -> nothing
941 $s = preg_replace( '/\bbinary\b/i', '', $s );
942 // auto_increment -> autoincrement
943 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
944 // No explicit options
945 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
946 // AUTOINCREMENT should immedidately follow PRIMARY KEY
947 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
948 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
949 // No truncated indexes
950 $s = preg_replace( '/\(\d+\)/', '', $s );
952 $s = preg_replace( '/\bfulltext\b/i', '', $s );
953 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
954 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
955 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
956 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
957 // INSERT IGNORE --> INSERT OR IGNORE
958 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
964 public function lock( $lockName, $method, $timeout = 5 ) {
965 $status = $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout );
967 $this->lockMgr
instanceof FSLockManager
&&
968 $status->hasMessage( 'lockmanager-fail-openlock' )
970 throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
973 return $status->isOK();
976 public function unlock( $lockName, $method ) {
977 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
981 * Build a concatenation list to feed into a SQL query
983 * @param string[] $stringList
986 function buildConcat( $stringList ) {
987 return '(' . implode( ') || (', $stringList ) . ')';
990 public function buildGroupConcatField(
991 $delim, $table, $field, $conds = '', $join_conds = []
993 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
995 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
999 * @param string $oldName
1000 * @param string $newName
1001 * @param bool $temporary
1002 * @param string $fname
1003 * @return bool|IResultWrapper
1004 * @throws RuntimeException
1006 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1007 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1008 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1009 $obj = $this->fetchObject( $res );
1011 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1014 $sql = preg_replace(
1016 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1018 $this->addIdentifierQuotes( $newName ),
1023 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1024 $this->queryLogger
->debug(
1025 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1027 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1031 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1033 // Take over indexes
1034 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1035 foreach ( $indexList as $index ) {
1036 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1040 if ( $index->unique
) {
1041 $sql = 'CREATE UNIQUE INDEX';
1043 $sql = 'CREATE INDEX';
1045 // Try to come up with a new index name, given indexes have database scope in SQLite
1046 $indexName = $newName . '_' . $index->name
;
1047 $sql .= ' ' . $indexName . ' ON ' . $newName;
1049 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1051 foreach ( $indexInfo as $indexInfoRow ) {
1052 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1055 $sql .= '(' . implode( ',', $fields ) . ')';
1057 $this->query( $sql );
1064 * List all tables on the database
1066 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1067 * @param string $fname Calling function name
1071 function listTables( $prefix = null, $fname = __METHOD__
) {
1072 $result = $this->select(
1080 foreach ( $result as $table ) {
1081 $vars = get_object_vars( $table );
1082 $table = array_pop( $vars );
1084 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1085 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1086 $endArray[] = $table;
1095 * Override due to no CASCADE support
1097 * @param string $tableName
1098 * @param string $fName
1099 * @return bool|IResultWrapper
1100 * @throws DBReadOnlyError
1102 public function dropTable( $tableName, $fName = __METHOD__
) {
1103 if ( !$this->tableExists( $tableName, $fName ) ) {
1106 $sql = "DROP TABLE " . $this->tableName( $tableName );
1108 return $this->query( $sql, $fName, self
::QUERY_IGNORE_DBO_TRX
);
1111 public function setTableAliases( array $aliases ) {
1112 parent
::setTableAliases( $aliases );
1113 foreach ( $this->tableAliases
as $params ) {
1114 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1117 $this->attachDatabase( $params['dbname'] );
1118 $this->alreadyAttached
[$params['dbname']] = true;
1122 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1123 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1124 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1126 "DELETE FROM $encTable WHERE name = $encName",
1128 self
::QUERY_IGNORE_DBO_TRX
1132 public function databasesAreIndependent() {
1139 protected function getBindingHandle() {
1140 return parent
::getBindingHandle();
1145 * @deprecated since 1.29
1147 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );